<!--
	Copyright (C) 2010 Ethan Gruber
	Numishare: http://code.google.com/p/numishare/
	Apache License 2.0
	
	Heavily modified from upload form developed by Orbeon	
-->
<html xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xforms="http://www.w3.org/2002/xforms"
	xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:xs="http://www.w3.org/2001/XMLSchema"
	xmlns="http://www.w3.org/1999/xhtml" xmlns:xxforms="http://orbeon.org/oxf/xml/xforms"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:fr="http://orbeon.org/oxf/xml/form-runner" xmlns:datetime="http://exslt.org/dates-and-times">
	<head>
		<title>Numishare: Upload CSV File</title>
		<link type="text/css" href="http://localhost:8080/cocoon/numishare/xforms.css"
			rel="stylesheet"/>
		<xforms:model>
			<xforms:instance id="files-instance">
				<!-- Start with placeholders for three files -->
				<files xmlns="">
					<file xsi:type="xs:anyURI" filename="" mediatype="" size=""/>
				</files>
			</xforms:instance>

			<xforms:instance id="url-generator">
				<config xmlns="">
					<url/>
					<content-type>text/plain</content-type>
				</config>
			</xforms:instance>			
			
			<xforms:instance id="xml-file">
				<root xmlns=""/>
			</xforms:instance>
			
			<xforms:instance id="processed-xml">
				<dsc xmlns=""/>
			</xforms:instance>			

			<xforms:instance id="mapping">
				<mapping xmlns=""/>
			</xforms:instance>

			<xforms:instance id="mapping-column-template">
				<column xmlns="" label="" value=""/>
			</xforms:instance>
			
			<xforms:instance id="imports">
				<imports xmlns=""/>
			</xforms:instance>
			
			<xforms:instance id="import-template">
				<import xmlns="" date="" filename=""/>
			</xforms:instance>
			
			<xforms:instance id="file-template">
				<file id="" xmlns=""/>
			</xforms:instance>

			<xforms:instance id="fields">
				<fields xmlns="">
					<field label="Document ID" value="id"/>
					<field label="Acquisition Information" value="acqinfo"/>
					<field label="Appraisal" value="appraisal"/>
					<field label="Artist" value="artist"/>
					<field label="Commentary" value="abstract"/>
					<field label="Color" value="color"/>
					<field label="Container" value="container"/>		
					<field label="Counterstamp" value="counterstamp"/>					
					<field label="Custodial History" value="custodhist"/>
					<field label="Date on Object" value="dob"/>
					<field label="Date: Textual" value="unitdate"/>
					<field label="Date: Machine Readable" value="unitdate-normal"/>
					<field label="Deity" value="deity"/>
					<field label="Die Axis" value="die_axis"/>
					<field label="Denomination" value="denomination"/>
					<field label="Department" value="department"/>
					<field label="Dimensions" value="dimensions"/>
					<field label="Dynasty" value="famname"/>					
					<field label="Edge" value="edge"/>
					<field label="Engraver" value="engraver"/>
					<field label="Identifier" value="unitid"/>
					<field label="Identifier Type" value="unitid-type"/>
					<field label="Image: Obverse Thumbnail" value="obverse_thumb"/>
					<field label="Image: Obverse Screen" value="obverse_screen"/>
					<field label="Image: Obverse Large" value="obverse_large"/>
					<field label="Image: Reverse Thumbnail" value="reverse_thumb"/>
					<field label="Image: Reverse Screen" value="reverse_screen"/>
					<field label="Image: Reverse Large" value="reverse_large"/>
					<field label="Issuer" value="isser"/>
					<field label="Maker" value="maker"/>
					<field label="Manufacture" value="manufacture"/>
					<field label="Material" value="material"/>
					<field label="Mintmark/Counterstamp" value="phystech"/>
					<field label="Obverse Grade" value="obverse_grade"/>
					<field label="Obverse Iconography" value="obverseType"/>
					<field label="Obverse Legend" value="obverseLegend"/>
					<field label="Obverse Symbol" value="obverseSymbol"/>
					<field label="Obverse Type" value="obverse_iconography"/>
					<field label="Personal Name" value="persname"/>
					<field label="Place: City" value="city"/>
					<field label="Place: Region" value="region"/>
					<field label="Place: State" value="state"/>
					<field label="Place: Other" value="geogname"/>
					<field label="Political Entity" value="corpname"/>
					<field label="Reference: Bibliographic Title" value="bibref-title"/>
					<field label="Reference: Bibliographic Number" value="bibref-num"/>
					<field label="Reference Hyperlink" value="ref"/>
					<field label="Reverse Grade" value="reverse_grade"/>
					<field label="Reverse Iconography" value="reverseType"/>
					<field label="Reverse Legend" value="reverseLegend"/>
					<field label="Reverse Symbol" value="reverseSymbol"/>
					<field label="Reverse Type" value="reverse_iconography"/>
					<field label="Script" value="script"/>
					<field label="Serial Number" value="sernum"/>
					<field label="Shape" value="shape"/>
					<field label="Signature" value="signature"/>
					<field label="Subject" value="subject"/>
					<field label="Subject--Event" value="subjectEvent"/>
					<field label="Subject--Issuer" value="subjectIssuer"/>
					<field label="Subject--Person" value="subjectPerson"/>
					<field label="Subject--Place" value="subjectPlace"/>
					<field label="Symbol" value="symbol"/>
					<field label="Title" value="unittitle"/>
					<field label="Undertype" value="undertype"/>
					<field label="Watermark" value="watermark"/>
					<field label="Weight" value="weight"/>
				</fields>
			</xforms:instance>

			<xforms:instance id="format-template">
				<format xmlns=""/>
			</xforms:instance>

			<xforms:instance id="formats">
				<formats xmlns="">
					<format label="Coin" value="coin"/>
					<format label="Medal" value="medal"/>
				</formats>
			</xforms:instance>
			
			<xforms:instance id="id-template">
				<id xmlns=""/>
			</xforms:instance>
			
			<xforms:instance id="current-id">
				<id xmlns=""/>
			</xforms:instance>
			
			<xforms:instance id="publish">
				<publish xmlns=""/>
			</xforms:instance>
			
			<!-- send to Solr -->
			<xforms:instance id="addIndex">
				<add xmlns=""/>
			</xforms:instance>
			
			<!-- Instance for Solr commit-->
			<xforms:instance id="sendCommit">
				<commit/>
			</xforms:instance>
			
			<!-- Solr optimize -->
			<xforms:instance id="optimizeIndex">
				<optimize/>
			</xforms:instance>

			<xforms:instance id="status">
				<selected/>
			</xforms:instance>

			<xforms:instance id="control-instance">
				<control xmlns="">
					<simple-upload-trigger/>
					<add-upload-trigger/>
					<remove-upload-trigger/>
				</control>
			</xforms:instance>
			
			<!-- load URLs from site_info.xml in eXist into form for Solr and CSS file -->
			<xforms:instance id="site-info">
				<site_info xmlns="">
					<url/>
					<solr_url/>					
				</site_info>
			</xforms:instance>

			<xforms:bind nodeset="instance('control-instance')">
				<xforms:bind nodeset="add-upload-trigger" readonly="false()"/>
				<xforms:bind nodeset="remove-upload-trigger"
					readonly="count(instance('files-instance')/file) le 1"/>
			</xforms:bind>

			<xforms:bind nodeset="instance('xml-file')">
				<xforms:bind nodeset="row[last()]">
					<xforms:bind constraint=".[count(elem[@mapping='unittitle']) &gt; 1]"/>
					<xforms:bind nodeset="format">
						<xforms:bind constraint="string-length(.) &gt; 0"/>
					</xforms:bind>
				</xforms:bind>
			</xforms:bind>			
			
			<!-- load site info -->
			<xforms:submission id="load-site-info" serialization="none" method="get"
				action="/exist/rest/db/numishare/site_info.xml" xxforms:username="admin"
				xxforms:password="admin" replace="instance" instance="site-info"/>
			
			<xforms:submission id="background-submission" method="post" replace="none"
				resource="test:">
				<xforms:action ev:event="xforms-submit-done">
					<xforms:setvalue ref="instance('url-generator')/url"
						value="instance('files-instance')/file"/>
					<xforms:insert nodeset="instance('xml-file')"
						origin="xxforms:call-xpl('oxf:/apps/numishare/xpl/convert-csv.xpl', 'file', instance('url-generator'), 'data')"/>
					<xforms:insert context="instance('xml-file')/row[last()]"
						origin="instance('format-template')"/>
					<xforms:action xxforms:iterate="instance('xml-file')/row[last()]/elem">
						<xforms:insert context="." origin="xxforms:attribute('mapping', '')"/>
					</xforms:action>
					<xforms:toggle case="map-columns"/>
				</xforms:action>
			</xforms:submission>
			
			<xforms:submission id="save-submission" ref="instance('processed-xml')/c[@id = instance('current-id')]" xxforms:username="admin"
				xxforms:password="admin"
				action="/exist/rest/db/numishare/ead/{instance('current-id')}.xml" method="put"
				replace="none">				
				<xforms:message ev:event="xforms-submit-error" level="modal">Save
				Error!</xforms:message>
				<xforms:action ev:event="xforms-submit-done">					
					<xforms:insert origin="instance('file-template')" context="instance('imports')/import[last()]" nodeset="./child::node()[last()]"/>
					<xforms:setvalue ref="instance('imports')/import[last()]/file[last()]/@id" value="instance('current-id')"/>
					<xforms:send submission="to-solr" if="instance('publish') = 'true'"/>
				</xforms:action>
				<!-- check to see if the document is already published to Solr -->
				<!--<xforms:send ev:event="xforms-submit-done" submission="query-solr-for-publication"/>-->
			</xforms:submission>
			
			<xforms:submission id="load-imports" serialization="none" method="get"
				action="/exist/rest/db/numishare/imports.xml" xxforms:username="admin"
				xxforms:password="admin" replace="instance" instance="imports"/>
			
			<xforms:submission id="save-imports" ref="instance('imports')"
				xxforms:username="admin" xxforms:password="admin"
				action="/exist/rest/db/numishare/imports.xml" method="put" replace="none">	
				<xforms:action ev:event="xforms-submit-done">
					<xforms:send submission="submit-commit"/>
					<xforms:setvalue ref="instance('status')">CSV file succesfully imported.</xforms:setvalue>					
				</xforms:action>				
				<xforms:message ev:event="xforms-submit-error" level="modal">Error saving imports record.</xforms:message>
			</xforms:submission>
			
			<xforms:submission id="to-solr" method="get" replace="instance" instance="addIndex"
				serialization="none"
				resource="{instance('site-info')/url}display/ead/{instance('current-id')}.solr">
				<xforms:message ev:event="xforms-submit-error" level="modal">Error transforming EAD
					guide to Solr document.</xforms:message>
				<xforms:send ev:event="xforms-submit-done" submission="publish-submission"/>
			</xforms:submission>
			<!-- post instance to Solr -->
			<xforms:submission id="publish-submission"
				action="{instance('site-info')/solr_url}update" ref="instance('addIndex')"
				instance="addIndex" replace="instance" method="post">								
				<xforms:message ev:event="xforms-submit-error" level="modal">Data Failed to POST to
					Solr. Index may be offline or URL is incorrect.</xforms:message>
			</xforms:submission>
			<!-- send commit -->
			<xforms:submission id="submit-commit" action="{instance('site-info')/solr_url}update"
			ref="instance('sendCommit')" instance="sendCommit" replace="none" method="post">
				<xforms:send submission="optimize" ev:event="xforms-submit-done"/>
			</xforms:submission>
			
			<!-- send optimize -->
			<xforms:submission id="optimize" action="{instance('site-info')/solr_url}update"
				ref="instance('optimizeIndex')" instance="optimizeIndex" replace="none"
				method="post">
				<xforms:message ev:event="xforms-submit-error" level="modal">Failed to optimize Solr
					index.</xforms:message>
			</xforms:submission>
			
			<xforms:action ev:event="xforms-model-construct-done">
				<xforms:send submission="load-imports"/>
				<xforms:send submission="load-site-info"/>
			</xforms:action>
		</xforms:model>
	</head>
	<body>
		<div class="form">
			<xforms:group ref="instance('status')/text()">
				<div class="success">
					<xforms:output ref="instance('status')"/>
				</div>
			</xforms:group>
			<xforms:switch>
				<xforms:case id="upload-file">
					<div class="section">
						<h3>Upload CSV file</h3>
						<p>Use this feature to import coins and medals into Numishare from a standard format CSV file.</p>						
						<p>Please select the file to upload:</p>
						<xforms:group ref="file">
							<div class="subsection">
								<!-- Upload field -->
								<fr:upload ref="." xxforms:size="60">
									<xforms:filename ref="@filename"/>
									<xforms:mediatype ref="@mediatype"/>
									<xxforms:size ref="@size"/>
								</fr:upload>
							</div>
						</xforms:group>
						<p>
							<xforms:submit submission="background-submission"
								ref="instance('control-instance')/simple-upload-trigger">
								<xforms:label>Upload</xforms:label>
							</xforms:submit>
						</p>
					</div>
				</xforms:case>
				<xforms:case id="map-columns">
					<xforms:group ref="instance('xml-file')/row[last()]">
						<div class="section">
							<h4>Map CSV columns to numismatic fields</h4>
							<p>Use the right column to select the semantically appropriate Numishare field to map to the CSV column heading, left.</p>

							<xforms:group ref=".[count(elem[@mapping='unittitle']) &lt; 1]">
								<div class="error">Title of object is required.</div>
							</xforms:group>
							
							<xforms:select ref="instance('publish')" appearance="full" >  								
								<xforms:item>
									<xforms:label>Publish</xforms:label>
									<xforms:value>true</xforms:value> 
								</xforms:item>								
							</xforms:select>

							<div>
								<xforms:select1 ref="format">
									<xforms:alert>Format is required.</xforms:alert>
									<xforms:label>Format</xforms:label>
									<xforms:item>
										<xforms:label>Select...</xforms:label>
										<xforms:value/>
									</xforms:item>
									<xforms:itemset nodeset="instance('formats')/format">
										<xforms:label ref="@label"/>
										<xforms:value ref="@value"/>
									</xforms:itemset>
								</xforms:select1>
							</div>

							<table>
								<thead>
									<tr>
										<th>CSV Column Label</th>
										<th>Numishare Field</th>
									</tr>
								</thead>
								<tbody>
									<xforms:repeat nodeset="elem">
										<tr>
											<td style="width:25%;">
												<xforms:output value="@name"/>
											</td>
											<td style="text-align:center;">
												<xforms:select1 ref="@mapping">
												<xforms:alert>Title cannot occur more than
												once.</xforms:alert>
												<xforms:item>
												<xforms:label>Select...</xforms:label>
												<xforms:value/>
												</xforms:item>
												<xforms:itemset nodeset="instance('fields')/field">
												<xforms:label ref="@label"/>
												<xforms:value ref="@value"/>
												</xforms:itemset>
												</xforms:select1>
											</td>
										</tr>
									</xforms:repeat>
								</tbody>
							</table>

							<!-- show import button only if it meets validation criteria -->
							<xforms:group ref=".[count(elem[@mapping='unittitle']) &gt; 0 and string-length(format) &gt; 0]">
								<xforms:trigger>
									<xforms:label>Import</xforms:label>
									<xforms:action ev:event="DOMActivate">
										<xforms:action xxforms:iterate="instance('xml-file')/row[not(position() = last())]" if=".[count(instance('xml-file')/row[last()]//elem[@mapping='id']) = 0]">
											<xforms:insert context="." origin="instance('id-template')"/>
											<xforms:setvalue ref="id" value="concat('n_', substring(string(digest( string( random( true ) ), 'MD5', 'hex' )), 1, 8))"/>
										</xforms:action>
										<xforms:insert nodeset="instance('processed-xml')"
											origin="xxforms:call-xpl('oxf:/apps/numishare/xpl/xml-to-ead.xpl', 'source', instance('xml-file'), 'finalized')"
										/>
										<!-- insert new import node -->
										<xforms:insert origin="instance('import-template')" context="instance('imports')" nodeset="./child::node()[last()]"/>
										<xforms:setvalue ref="instance('imports')/import[last()]/@date" value="concat(datetime:dateTime(), 'Z')"/>
										<xforms:setvalue ref="instance('imports')/import[last()]/@filename" value="instance('files-instance')/file/@filename"/>
										
										<!-- iterate through new components to save each one individually to eXist -->
										<xforms:action xxforms:iterate="instance('processed-xml')/c">
											<xforms:setvalue ref="instance('current-id')" value="context()/@id"/>
											<xforms:send submission="save-submission"/>
										</xforms:action>
										<xforms:send submission="save-imports"/>
									</xforms:action>
								</xforms:trigger>
							</xforms:group>

						</div>
					</xforms:group>
				</xforms:case>
			</xforms:switch>

			<!--<widget:xforms-instance-inspector id="orbeon-xforms-inspector"
				xmlns:widget="http://orbeon.org/oxf/xml/widget"/>-->
		</div>
	</body>
</html>
